package Admin

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/jwt"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/Admin"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
)

type AdminLogin struct {
	controllers.MainController
}

type AdminLoginForm struct {
	Uuid     string
	Password string
}

func (this *AdminLogin) Post() {
	var alf AdminLoginForm
	r := this.Ctx.Request
	decoder := json.NewDecoder(r.Body)
	err1 := decoder.Decode(&alf)
	if err1 != nil {
		body := map[string]interface{}{"code": 300}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//管理员登录信息校验
	//管理员信息插表
	db := models.ConnDb()
	defer db.Close()
	var ta Admin.TbAdmin
	err2 := db.Where("user_id = ?", alf.Uuid).Find(&ta).Error
	if err2 != nil {
		body := map[string]interface{}{"code": 301, "data": "验证失败", "msg": "用户名不存在"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	if alf.Password == ta.Password {
		body := map[string]interface{}{"code": 200, "data": "验证成功"}
		token := jwt.GenToken() //生成一个token
		this.Ctx.SetCookie("uuid", token, 1000000, "/")
		rd := redis.R.Conn
		defer rd.Close()
		_, err4 := rd.Set(token, alf.Uuid)
		if err4 != nil {
			body = map[string]interface{}{"code": 305, "data": "验证失败", "msg": "服务器异常"}
			this.Data["json"] = body
			this.ServeJSON()
			return
		}
		_, err5 := rd.Expire(token, 1000000) //token生存周期
		if err5 != nil {
			body = map[string]interface{}{"code": 305, "data": "验证失败", "msg": "服务器异常"}
			this.Data["json"] = body
			this.ServeJSON()
			return
		}
		this.Data["json"] = body
		this.ServeJSON()
		return
	} else {
		body := map[string]interface{}{"code": 302, "data": "验证失败", "msg": "密码错误"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}

}
